<template>
  <div>
    <el-button type="primary" icon="el-icon-plus" @click="openDia">添加</el-button>
    <el-dialog ref="dia" :close-on-click-modal="false" :close-on-press-escape="false" :visible.sync="dialogFormVisible" :append-to-body="true" custom-class="r-dialog" title="部门选择" top="5vh" width="20%">
      <el-tree ref="tree" :data="jsonTree" style="margin-top: 12px;" show-checkbox default-expand-all node-key="id" highlight-current />
      <span v-if="isShowFoot" slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmHandle">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import { getPositionAuthRoleTree } from '@/api/admin/auth/positionAuth'
import { getJsonTree } from '@/utils/index'
import formMixins from '@/mixins/formMixins'

export default {
  name: 'DepartmentTree',
  components: {},
  mixins: [formMixins],
  props: {
    isShowFoot: {
      type: Boolean,
      default() {
        return true
      }
    }
  },
  data() {
    return {
      dialogFormVisible: false,
      key: '',
      tree: [],
      loading: false,
      list: []
    }
  },
  computed: {
    jsonTree() {
      this.tree.forEach(el => (el.label = el.text))
      this.tree.forEach(el => (el.parentId = el.parent))
      return getJsonTree(this.tree)
    }
  },
  mounted() {},
  methods: {
    // 树加载
    searchTree() {
      this.loading = true
      getPositionAuthRoleTree()
        .then(res => {
          this.deleteRes(res)
          this.loading = false
          this.tree = res
        })
        .catch(err => {
          this.loading = false
        })
    },
    // 删除无效数据(无父节点)
    deleteRes(res) {
      const result = []
      for (let i = 0; i < res.length && res[i].id != null; i++) {
        const pid = res[i].parent
        const oid = res[i].id
        result[oid] = pid
      }
      for (let j = 0; j < res.length; j++) {
        // 一级父节点跳过
        if (res[j].parent === '#') continue
        if (res[j] && result[res[j].parent] == null) {
          const index = j
          j = 0
          delete result[res[index].id]
          res.splice(index, 1)
        }
      }
    },
    openDia() {
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.searchTree()
      })
    },
    confirmHandle() {
      this.list = []
      this.list = this.$refs.tree.getCheckedNodes(true)
      this.$emit('getTreeList', this.list)
      if (this.list.length === 0) {
        this.$message({
          type: 'info',
          message: '请选择数据!'
        })
        return false
      }
    }
  }
}
</script>

<style scoped>
</style>
